package com.saikei.demoapp.util

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.saikei.demoapp.R
import com.saikei.demoapp.base.FragmentContainActivity

class IntentStarter(private val mContentObj: Any) {

    private var mBundle: Bundle? = null
    private var mActivityFlag: Int = 0

    companion object {
        const val INTENT_FRAGMENT_NAME = "INTENT_FRAGMENT_NAME"
        fun create(context: Any): IntentStarter = IntentStarter(context)
    }

    fun withData(vararg data: Any): IntentStarter {
        val newBundle = IntentUtils.obtainArg(*data)
        mBundle = newBundle
        return this
    }

    fun startActivity(targetActivity: Class<out Activity>) {
        val context = IntentUtils.contextObjToContext(mContentObj) ?: throw IllegalArgumentException("Invalid context: $mContentObj")
        val intent = Intent(context, targetActivity).apply {
            flags = mActivityFlag
            putExtras(mBundle ?: Bundle())
        }
        start(context, intent)
    }

    fun startFragment(
        fragmentClass: Class<out Fragment>,
    ) {
        val name = fragmentClass.name
        if (this.mBundle == null) {
            this.mBundle = Bundle()
        }
        this.mBundle?.putString(INTENT_FRAGMENT_NAME, name)
        startActivity(FragmentContainActivity::class.java)
    }

    private fun start(context: Context, intent: Intent) {
        when (mContentObj) {
            is Fragment -> {
                val fragment = mContentObj as Fragment
                fragment.startActivity(intent)
                fragment.activity?.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left)
            }
            is AppCompatActivity -> {
                val activity = mContentObj as AppCompatActivity
                activity.startActivity(intent)
                activity.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left)
            }
            else -> throw IllegalArgumentException("Unsupported context type: ${mContentObj::class}")
        }
    }

    fun finish() {
        when (mContentObj) {
            is Fragment -> {
                val fragment = mContentObj as Fragment
                fragment.activity?.apply {
                    overridePendingTransition(R.anim.slide_out_left, R.anim.slide_out_right)
                }
            }
            is AppCompatActivity -> {
                val activity = mContentObj as AppCompatActivity
                activity.apply {
                    overridePendingTransition(R.anim.slide_out_left, R.anim.slide_out_right)
                }
            }
            else -> throw IllegalArgumentException("Unsupported context type: ${mContentObj::class}")
        }
    }

}

